const Service = require('egg').Service;
const createRule = {
    username: {
        type: 'email',
    },
    password: {
        type: 'password',
        compare: 're-password',
    },
}
class NewsService extends Service {
    async list(page = 1) {

        // 校验表单
        this.ctx.validate(createRule);

        // read config
        const { serverUrl, pageSize } = this.config.news;

        // use build-in http client to GET hacker-news api
        const { data: idList } = await this.ctx.curl(`${serverUrl}/topstories.json`, {
            data: {
                orderBy: '"$key"',
                startAt: `"${pageSize * (page - 1)}"`,
                endAt: `"${pageSize * page - 1}"`,
            },
            dataType: 'json',
        });

        // parallel GET detail
        const newsList = await Promise.all(
            Object.keys(idList).map(key => {
                const url = `${serverUrl}/item/${idList[key]}.json`;
                return this.ctx.curl(url, { dataType: 'json' });
            })
        );
        return newsList.map(res => res.data);
    }
    async uploadFile() {
        const { ctx } = this;
        console.log(ctx.request.body);
        console.log('got %d files', ctx.request.files.length);
        for (const file of ctx.request.files) {
            console.log('field: ' + file.fieldname);
            console.log('filename: ' + file.filename);
            console.log('encoding: ' + file.encoding);
            console.log('mime: ' + file.mime);
            console.log('tmp filepath: ' + file.filepath);
            let result;
            try {
                // 处理文件，比如上传到云端
                result = await ctx.oss.put('egg-multipart-test/' + file.filename, file.filepath);
            } finally {
                // 需要删除临时文件
                await fs.unlink(file.filepath);
            }
            console.log(result);
        }
    }
    /**
     * 文件流
     * @returns {Promise<void>}
     */
    async upload() {
        const ctx = this.ctx;
        const stream = await ctx.getFileStream();
        const name = 'egg-multipart-test/' + path.basename(stream.filename);
        // 文件处理，上传到云存储等等
        let result;
        try {
            result = await ctx.oss.put(name, stream);
        } catch (err) {
            // 必须将上传的文件流消费掉，要不然浏览器响应会卡死
            await sendToWormhole(stream);
            throw err;
        }

        ctx.body = {
            url: result.url,
            // 所有表单字段都能通过 `stream.fields` 获取到
            fields: stream.fields,
        };
    }
}

module.exports = NewsService;
